﻿package hapi.mvc.action;

interface Action {
	public function run(params:Dynamic);
}

interface HttpAction {
	public function doGet(params:Dynamic);
	public function doPost(params:Dynamic);
}


class ShowAction<T> implements Action {
	
	private var finder:Int -> T;
	
	public function run(params:Dynamic) {
		try {
			var object:T  = finder(params.id);
			display(object);
		}catch (FindException e) {
			new ExceptionAction(e).run(params);
		}
	}
}
class DeleteAction<T> implements Action {
	
	private var delete:Int->T;
	private var forward:Action;
	
	public function run(params:Dynamic) {
		try {
			delete(params.id);
			forward.run(params);
		}catch (DeleteException e) {
			new ExceptionAction(e).run(params);
		}
	}
}
class CreateAction<T> implements Action {
	
	var doCreate:Dynamic - > T;
	var forward:Action;
	
	public function new(doCreate, forward) {
		this.doCreate = doCreate;
	}
	
	public function run(params:Dynamic) {
		decision.run(params);
	}
	
	private function doGet(params:Dynamic) {
		//display form
	}
	
	private function doPost(params:Dynamic) {
		//creates object and redirects or displays validation errors
		try {
			var obj = doCreate(params);
			forward.run(params);
		}catch (CreateException e) {
			displayError(e);
		}
	}
	
	private function displayForm() {
		
	}
	
	private function displayError(e) {
		
	}
}

class HttpRedirectAction {
	
	public var url(default, null):String;
	
	public function new(url:String) {
		this.url = url;
	}
	
	public function run(params:Dynamic) {
		Web.redirect(url);
	}
}


class DecisionAction implements Action {
	
	private var decide:Dynamic -> Bool;
	private var onTrue:Dynamic->Void;
	private var onFalse:Dynamic->Void;
	
	public function new(decide, onTrueAction, onFalseAction) {
		this.decide = decide;
		this.onTureAction = onTrueAction;
		this.onFalseAction = onFalseAction;
	}
	
	public function run(params:Dynamic) {
		if (decide(params) {
			onTureAction.run(params);
		}else {
			onFalseAction.run(params);
		}
	}
}
class OnHttpPostDispatcherAction extends DispatcherAction {
	
}

using StringUtil;
HttpDecitions {
	
	public static function isPost(params) {
		return "POST".iEquals(Web.getMethod());
	}
	
}

class StringUtil {
	public function iEquals(a:String, b:String) {
		return a.toUpperCase() == b.toUpperCase();
	}
}

class ActionDispatcher implements Action {
	
	public function run(params:Dynamic);
	
}